﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PeiYue.Api.Controllers.BASE;
using PeiYue.Common.Helper;
using PeiYue.Common.HttpContextUser;
using PeiYue.IServices;
using PeiYue.IServices.Purchase;
using PeiYue.Model;
using PeiYue.Model.Dto.Purchase;
using PeiYue.Model.Models.Purchase;

namespace PeiYue.Api.Controllers.Purchase
{
    /// <summary>
    /// 供应商
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SupplierController : BaseController<Supplier>
    {
        readonly IMapper _mapper;
        readonly ISupplierServices _supplierServices;
        readonly ISysUserInfoServices _sysUserInfoServices;
        readonly ISupplierSignServices _supplierSignServices;
        IUser _user;
        public SupplierController(ISupplierServices supplierServices, ISysUserInfoServices sysUserInfoServices,
            ISupplierSignServices supplierSignServices,
            IUser user, IMapper mapper) : base(supplierServices, user)
        {
            _supplierServices = supplierServices;
            _sysUserInfoServices = sysUserInfoServices;
            _supplierSignServices = supplierSignServices;
            _user = user;
            this._mapper = mapper;
        }
        /// <summary>
        /// 获取供应商列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<SupplierList>>> GetSupplierList()
        {
            string where = string.Empty;
            var today = DateTime.Now.ToString("yyyy-MM-dd");
            var yestoday = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            var tomorrow = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            if (DateTime.Now.Hour >=23)
            {
                where= " CreateTime >=@today and CreateTime <@tomorrow  ";
            }
            else
            {
                where= " CreateTime>=@yestoday and CreateTime<@today " ;
            }
            var list = await _supplierServices.SqlQueryList<SupplierList>(@$"select 编号 as SupplierCode,简称 as SupplierName,isnull(Convert(varchar(50), s.CreateTime, 120), '') SignTime from[供应链].[dbo].[v供应商] g
            Left Join OMS.dbo.SupplierSign s on g.编号 = s.SupplierCode  and {where} 
            where 合作状态 = '正常'",
            new List<SqlSugar.SugarParameter>() {
                new SqlSugar.SugarParameter("@today", $"{today } 23:00:00"),
                new SqlSugar.SugarParameter("@tomorrow", $"{tomorrow } 23:00:00"),
                new SqlSugar.SugarParameter("@yestoday", $"{yestoday } 23:00:00"),

            });
            list.ForEach(t => {
                t.SupplierId = Convert.ToInt32(t.SupplierCode.Substring(1));
            });
            return new MessageModel<List<SupplierList>>()
            { msg = "获取成功", success = true, response = list.OrderBy(t=>t.SupplierId).ToList() };

        }

        /// <summary>
        /// 查询分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<SupplierDTO>>> GetPage([FromQuery] SearchSupplierDTO querymodel)
        {
            Expression<Func<Supplier, bool>> ex = t => 1 == 1;

            if (querymodel.status == null || querymodel.status == 0)
                ex = ex.And(t => t.status != 3);
            else
                ex = ex.And(t => t.status == querymodel.status);

            //PageModel<SupplierDTO> data = new PageModel<SupplierDTO>() { };

            var list = await _supplierServices.QueryPage(ex, querymodel.pageIndex, querymodel.pageSize, " Id desc ");

            //做转换 
            var page = _mapper.Map<PageModel<SupplierDTO>>(list);

            if (list.dataCount > 0)
            {

                var users = page.data.Select(d => d.create_user).ToList().Union(page.data.Select(d => d.update_user).ToList()).Distinct().ToArray();
                var allUsers = await _sysUserInfoServices.QueryByIDs(users);

                page.data.ForEach(item =>
                {
                    item.create_names = allUsers.Where(u => u.uID == item.create_user).FirstOrDefault()?.uRealName;
                    item.update_names = allUsers.Where(u => u.uID == item.update_user).FirstOrDefault()?.uRealName;
                });
            }
            return new MessageModel<PageModel<SupplierDTO>>()
            { msg = "获取成功", success = true, response = page };
        }

        /// <summary>
        /// 同步ERP供应商
        /// </summary> 
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<string>> GetERPSupper()
        {
            var data = new MessageModel<string>();

            string sql = @" insert into[OMS].[dbo].[oms_srm_supplier]
      ([unit_id], codec, [namec], [names], [street], [market], [stall], [contact], [cellphone], [status]
      , update_time, [create_time], [update_user], [create_user])
 select 0 unit_id, [编号], [名称], [简称], [经营地址], [所在市场], [摊位号], [联系人姓名], [联系人电话],
  [状态], [制单日期], [制单日期], 1 update_user, 1 create_user
  from[供应链].[dbo].[v供应商] old
  left join[OMS].[dbo].[oms_srm_supplier] new on old.编号 = new.codec
  where new.codec is null

  update[OMS].[dbo].[oms_srm_supplier]
  set[namec] =  [名称],[names]=[简称],[street]=[经营地址],[market]=[所在市场],[stall]=[摊位号],[contact]=[联系人姓名],[status]=[状态]
  ,update_time =[制单日期],[update_user]= 1
  from[供应链].[dbo].[v供应商] old
  left join[OMS].[dbo].[oms_srm_supplier] new on old.编号 = new.codec
  where new.codec is not null and new.update_time != CAST(old.制单日期 as datetime2(0))";
            int count = await BaseSer.ExecuteCommand(sql, null);
            data.success = true;
            data.msg = $"操作成功,更新{count}行";
            return data;
        }
        /// <summary>
        /// 供应商签到信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<SigninResponseDto>> GetSignin()
        {
            var data = new MessageModel<SigninResponseDto>();
            var model = await _supplierSignServices.QueryModel(t => t.CreateUser == _user.ResId && t.CreateTime >= DateTime.Now.Date);
            if (model != null)
            {
                data.response = new SigninResponseDto() {
                    Address = model.Address,
                    SigninDate = model.CreateTime,
                    Lon = model.Lon,
                    Lat=model.Lat
                };
            }
            return data;
        }
        /// <summary>
        /// 供应商签到(PC)
        /// </summary>
        /// <param name="dto">签到参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> SupplierSign([FromBody]SigninDto dto)
        {
            var data = new MessageModel<string>();
            var model = new SupplierSignDao();
            var today =Convert.ToDateTime( $"{  DateTime.Now.ToString("yyyy-MM-dd") } 23:00:00");
            var yestoday = Convert.ToDateTime($"{  DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") } 23:00:00");
            var tomorrow = Convert.ToDateTime($"{  DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") } 23:00:00");
            if (DateTime.Now.Hour >= 23)
            {
                model = await _supplierSignServices.QueryModel(t => t.SupplierCode == dto.SupplierCode && t.CreateTime >= today && t.CreateTime<tomorrow);
            }
            else
            {
                model = await _supplierSignServices.QueryModel(t => t.SupplierCode == dto.SupplierCode && t.CreateTime >= yestoday && t.CreateTime < today);
            }
            if (model == null)
            {
                model = new SupplierSignDao();
                model.Lon = 0;
                model.Lat = 0;
                model.Address = "";
                model.CreateTime = DateTime.Now;
                model.CreateUser = _user.ResId;
                model.SupplierCode = dto.SupplierCode;
                model.SupplierName = dto.SupplierName;
                if (DateTime.Now.Hour >= 23)
                {
                    model.DeliveryDate = DateTime.Now.AddDays(1).Date;
                }
                else
                {
                    model.DeliveryDate = DateTime.Now.Date;
                }
                await _supplierSignServices.Add(model);
                return data;
            }
            else
            {
                data.status = 500;
                data.msg = "今天已签到";
                return data;
            }
        }
        /// <summary>
        /// 供应商签到(小程序)
        /// </summary>
        /// <param name="dto">签到参数</param>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public async Task<MessageModel<string>> Signin([FromBody]SigninRequestDto dto)
        {
            var data = new MessageModel<string>();
            var model =await _supplierSignServices.QueryModel(t => t.CreateUser == _user.ResId && t.CreateTime>= DateTime.Now.Date);
            if (model == null)
            {
                model = new SupplierSignDao();
                model.Lon = dto.Lon;
                model.Lat = dto.Lat;
                model.Address = dto.Address;
                model.CreateTime = DateTime.Now;
                model.CreateUser = _user.ResId;
                if (DateTime.Now.Hour >= 23)
                {
                    model.DeliveryDate = DateTime.Now.AddDays(1).Date;
                }
                else
                {
                    model.DeliveryDate = DateTime.Now.Date;
                }
                await _supplierSignServices.Add(model);
                return data;
            }
            else
            {
                data.status = 500;
                data.msg = "今天已签到";
                return data;
            }
        }
        /// <summary>
        /// 获取当天日期
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<string>> GetDate()
        {
            var data = new MessageModel<string>();
            data.response = DateTime.Now.ToString();
            return data;
        }

    }
}
